import React, { Component } from 'react';
import { connect } from 'react-redux';
import { base, ajax, getMultiLang, toast } from 'nc-lightapp-front';
const { NCSelect, NCIcon, NCFormControl, NCCheckbox, NCMessage, NCDiv } = base;
const NCOption = NCSelect.NCOption;
import './index.less';
import classnames from 'classnames';
import sscOpenTo from 'src/erm/sscrppublic/common/utils/sscOpenTo';


class WorkbenchSearcharea extends Component {
    constructor(props) {
        super();
        this.state = {
            menuShowType: {
                type: "icon-Group",
                title: '',
                showMore: false,
                barcodeVal: '',
                autoOpenChecked: false, //自动打开
                hasBarCode: false
            },
            multiLang: {},
            hideFat: false
        }
    }/**
     * 初始化查询选择
     */
    initSelect(keys) {
        let newStates = {};
        keys.forEach(item => {
            newStates[item] = null;
        })
        this.setState(newStates);
    }

    handleConditionChange(attrcode, data) {
        let newState = {};
        newState[attrcode] = data;
        let currentTabKey = this.props.currentTabKey || '';
        newState[currentTabKey + attrcode] = data;
        this.setState(newState);
        this.props.handleConditionChange(attrcode, data);
        this.updateTradetypeOptions()
    }

    thinFilterChange(attrcode, data) {
        this.scrollByThinSelectChange = true;
        this.handleConditionChange(attrcode, data);
    }

    menuClick = () => {
        if (this.state.menuShowType.type == "icon-xingzhuang") {
            this.setState({ menuShowType: { type: "icon-Group", title: this.state.multiLang['1056common-0007']/*缩略显示*/ } });
            if (this.props.showTypeClick != null) {
                this.props.showTypeClick("list");
            }
        } else {
            this.setState({ menuShowType: { type: "icon-xingzhuang", title: this.state.multiLang['1056common-0008']/*列表显示*/ } });
            if (this.props.showTypeClick != null) {
                this.props.showTypeClick("card");
            }
        }
    }

    componentDidUpdate() {
        this.updateTradetypeOptions()
    }

    updateTradetypeOptions = () => {
        const pk_tradetype = document.getElementById('trade-type-condition')
        if (pk_tradetype) {
            let children = pk_tradetype.children
            const PK_TRADE_TYPE_WIDTH = pk_tradetype.clientWidth
            let total_width = 70
            let sclice_idx = -1
            for (let i = 0; i < children.length; i++) {
                if (children[i].tagName == 'SPAN') continue
                children[i].style.display = 'inline-block'
            }
            for (let i = 0; i < children.length; i++) {
                if (children[i].tagName == 'SPAN') continue
                // total_width += children[i].offsetWidth + 20
                total_width += children[i].offsetWidth
                if (total_width >= PK_TRADE_TYPE_WIDTH) {
                    sclice_idx = i
                    break
                }
            }
            // console.log('sclice_idx: ', sclice_idx)
            if (sclice_idx > -1) {
                if (!this.state.showMore) {
                    for (let i = 0; i < children.length; i++) {
                        if (children[i].tagName == 'SPAN') continue
                        if (i >= sclice_idx) {
                            children[i].style.display = 'none'
                        } else {
                            children[i].style.display = 'inline-block'
                        }
                    }
                }
            }
            if (sclice_idx == -1) {
                let moreViewBtn = document.getElementById('more-view-btn')
                if (moreViewBtn) {
                    moreViewBtn.style.display = 'none'
                }
            } else {
                let moreViewBtn = document.getElementById('more-view-btn')
                if (moreViewBtn) {
                    if (this.state.showMore) {
                        moreViewBtn.style.display = 'none'
                    } else {
                        moreViewBtn.style.display = 'block'
                    }
                }
            }
        }
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.conditions != this.props.conditions) {
            this.setState({ showMore: false }, () => { this.updateTradetypeOptions() })
        }
        return true
    }

    barcodeQuery = () => {
        const {
            barcodeApi,
            queryKey,
            queryDataCallback,
            cusType
        } = this.props

        const {
            barcodeVal,
            autoOpenChecked,
            hasBarCode
        } = this.state

        if (!barcodeApi) return

        if (!hasBarCode && this.props.queryData) { //当单据码为空时，重新查询数据； 作业调度不传queryData
            this.props.queryData();
            return;
        }

        barcodeApi({
            data: {
                ...queryKey,
                barcode: barcodeVal
            },
            success: (data) => {
                const {
                    tasklist: {
                        rows
                    }
                } = data;

                queryDataCallback(data);

                if (rows.length == 0) { // 提示为空
                    if (this.props.taskTakeActionByBarCode) { //我的作业 查询为空时需要调用任务提取接口
                        this.props.taskTakeActionByBarCode(barcodeVal, (data) => {
                            if (data.tasklist.rows.length) {
                                this.autoOpenBarcodePage(data.tasklist.rows);
                            }
                        });
                    } else { // 作业调度直接报提示
                        toast({ color: 'warning', content: this.state.multiLang['1056common-0016'] }); /*扫描条码未查询到单据*/
                    }
                } else {
                    this.autoOpenBarcodePage(rows);
                }
            }
        })
    }

    autoOpenBarcodePage = (rows) => {
        const {
            autoOpenChecked,
            hasBarCode
        } = this.state
        if (autoOpenChecked && hasBarCode) { // 自动打开
            const { values: {
                billtypecode,
                transtypecode,
                busiid
            } } = rows[0]

            ajax({
                url: '/nccloud/sscrp/rpbill/BrowseBillAction.do',
                data: {
                    billtypeCode: billtypecode.value,
                    transtypeCode: transtypecode.value,
                    billid: busiid.value
                },
                success: (data) => {
                    sscOpenTo(this.props.ncProps, data.data.system, [
                        data.data.url,
                        {
                            ...data.data.data,
                            scene: this.props.cusType.split('_')[1]
                        }
                    ])
                }
            })
        }
    }

    resetState = () => {
        let newState = this.state
        for (let attr in newState) {
            if (attr != 'menuShowType' && attr != 'multiLang') {
                newState[attr] = ''
                if (attr == 'fuzzyQueryValue') {
                    newState[attr] = undefined;
                }
            }

        }
        this.setState(newState)
    }

    componentDidMount() {
        getMultiLang({
            moduleId: 1056, domainName: 'sscrp', currentLocale: 'zh-CN', callback: (json) => {
                this.setState({
                    multiLang: json,
                    menuShowType: { ...this.state.menuShowType, title: json['1056common-0007'] } /*缩略显示*/
                })
            }
        })
    }

    changeHideFat(status) {
        this.setState({
            hideFat: status
        })
        this.props.ncProps.table.updateTableHeight();
    }

    render() {
        const { conditions, cusType, twoColNums } = this.props;
        const { fuzzyquerychild } = this.props;
        const { onFuzzyChange, onFuzzySelected, hideBarCode } = this.props;
        const { showMore } = this.state;

        let getActive = (conditionOne, key) => {
            let isActive = false;
            let currentTabKey = this.props.currentTabKey || '';
            let val = this.state[currentTabKey + conditionOne.attrcode];

            if (conditionOne.initialvalue && conditionOne.initialvalue.value == key) {
                if (val) {
                    let isSetDefaultVal = true;
                    conditionOne.options.forEach((opt) => {
                        if (opt.value == val) {
                            isSetDefaultVal = false;
                        }
                    })
                    if (isSetDefaultVal) {
                        isActive = true;
                        this.setState({
                            [currentTabKey + conditionOne.attrcode] : null
                        })
                    }
                } else {
                    isActive = true;
                }
            }

            if (val == key ) {
                isActive = true;
            }

            if (isActive) {
                return 'active nc-theme-activ-area-bgc nc-theme-activ-font-c';
            } else {
                return ''
            }


        }

        let getCondition = (conditionOne) => {
            let ulId = (conditionOne.attrcode === 'pk_tradetype' || conditionOne.attrcode === 'transtypecode') ? 'trade-type-condition' : ''
            switch (conditionOne.itemtype) {
                case 'select':
                    return (
                        <ul id={ulId}>
                            {
                                conditionOne.options.map((one, index) => {
                                    return (
                                        <li
                                            key={"conditionOne_" + conditionOne.itemtype + "_" + index}
                                            className={"query-key " + getActive(conditionOne, one.value) + " nc-theme-common-font-c nc-theme-activ-font-c"}
                                            onClick={this.handleConditionChange.bind(this, conditionOne.attrcode, one.value)}
                                        >{one.display}</li>
                                    )
                                })
                            }
                            <span
                                style={{
                                    display: (conditionOne.attrcode === 'pk_tradetype' || conditionOne.attrcode === 'transtypecode') && showMore ? 'block' : 'none'
                                }}
                                className='arrow-up'
                                onClick={() => { this.setState({ showMore: false }, () => { this.updateTradetypeOptions() }) }}
                            >
                                {this.state.multiLang['1056common-0009']/*收起*/}
                            </span>
                        </ul>
                    );
                case 'select':
                    return (
                        <input />
                    );
                default:
                    return null;
            }
        }

        let getQueyKeyWithThinStyle = () => {
            let parentJsx = []
            let jsx = [];
            /**
                conditions.forEach((item) => {
                    let options = item.options;
                    let itemJsx = (
                        <div className='ncc-filter-wrap'>
                            <span className='filter-label'>
                                {item.label}：
                            </span>
                            <NCSelect
                                fieldid={item.attrcode}
                                className='select-filter'
                                value={this.state[item.attrcode] || item.initialvalue.value}
                                onChange={this.thinFilterChange.bind(this, item.attrcode)}
                                showClear={false}
                            >
                                {options.map((opt) => {
                                    return <NCOption value={opt.value}>{opt.display}</NCOption>
        
                                })}
                            </NCSelect>
                        </div>
                    )
                    jsx.push(itemJsx);
                });
             * **/

            if (cusType == "rp") {
                jsx.push(
                    <div className={'ncc-filter-wrap'}>
                        <span className='filter-label'>{this.state.multiLang['1056common-0011']/*模糊搜索：*/}：</span>
                        <NCSelect
                            fieldid="fuzzy-query"
                            className="fuzzyquery-thin"
                            height="24px"
                            tags
                            supportSearch={true}
                            searchPlaceholder={this.state.multiLang['1056common-0012']/*标签模式*/}
                            placeholder={this.state.multiLang['1056common-0013']/*模糊查询*/}
                            data={fuzzyquerychild}
                            value={this.state.fuzzyQueryValue}
                            onSearch={onFuzzyChange.bind(this)}
                            onChange={(data) => {
                                this.scrollByThinSelectChange = true;
                                this.setState({
                                    fuzzyQueryValue: data
                                });
                                onFuzzySelected.call(this, data)
                            }}
                        >
                        </NCSelect>
                    </div>
                );
            } else if (cusType.indexOf("tp") > -1) {
                jsx.push(
                    <div>

                        <div
                            className={classnames('ncc-filter-wrap thin-barcode', { "barcode-focus": this.state.barcodeVal && this.state.barcodeVal.length > 0 })}
                            style={{ display: hideBarCode ? 'none' : '' }}>
                            <span className='filter-label'>{this.state.multiLang['1056common-0014']/*更多条件：*/}：</span>
                            <NCFormControl
                                fieldid="barcode-query"
                                value={this.state.barcodeVal}
                                onChange={(val) => {
                                    if (val) {
                                        this.setState({ barcodeVal: val, hasBarCode: true })
                                    } else {
                                        this.setState({ barcodeVal: val, hasBarCode: false }, () => {
                                            this.barcodeQuery()
                                        })
                                    }
                                }}
                                type='search'
                                onSearch={this.barcodeQuery}
                                placeholder={this.state.multiLang['1056common-0051']/*条码扫描*/}
                            />
                            <i className='iconfont icon-saoyisao'></i>
                        </div>
                        <div className="ncc-filter-wrap">
                            <span className='filter-label'>{this.state.multiLang['1056common-0011']/*模糊搜索：*/}：</span>
                            <NCSelect
                                fieldid="fuzzy-query"
                                className="fuzzyquery-thin"
                                height="24px"
                                tags
                                supportSearch={true}
                                searchPlaceholder={this.state.multiLang['1056common-0012']/*标签模式*/}
                                placeholder={this.state.multiLang['1056common-0013']/*模糊查询*/}
                                data={fuzzyquerychild}
                                value={this.state.fuzzyQueryValue}
                                onSearch={onFuzzyChange.bind(this)}
                                onChange={(data) => {
                                    this.setState({
                                        fuzzyQueryValue: data
                                    });
                                    onFuzzySelected.call(this, data)
                                }}
                            >
                            </NCSelect>
                        </div>
                        <div className="ncc-filter-wrap" style={{ height: '35px', color: '#999', display: hideBarCode ? 'none' : '' }}>
                            <NCCheckbox
                                onChange={() => {
                                    this.setState({ autoOpenChecked: !this.state.autoOpenChecked })
                                }}
                                checked={this.state.autoOpenChecked}
                            >{this.state.multiLang['1056common-0015']/*自动打开：*/}</NCCheckbox>
                        </div>
                        <div className='cashier-reject-thin'
                            style={{ display: this.props.showCashierReject ? 'block' : 'none' }}
                        >
                            <NCCheckbox
                                checked={this.props.queryKey.iscmpreject == 'Y' ? true : false}
                                onChange={(val) => {
                                    this.setState({
                                        showCahierReject: val
                                    })
                                    this.props.handleConditionChange('iscmpreject', val ? 'Y' : 'N');
                                }}
                            >{this.state.multiLang['1056common-0050'] || '出纳驳回'/* 出纳驳回 */}</NCCheckbox>
                        </div>
                    </div>
                )
            }

            parentJsx.push(
                <div className="left ">
                    {jsx}
                </div>
            )
            parentJsx.push(
                <div className='right filter-bar-control-btn-wrap'>
                    <i className='menu-type-icon iconfont icon-Artboardfuben nc-theme-btn-secondary' onClick={
                        () => {
                            this.changeHideFat(false);
                        }
                    }></i>
                    <i
                        className={`menu-type-icon iconfont ${this.state.menuShowType.type} nc-theme-btn-secondary`}
                        title={this.state.menuShowType.title}
                        onClick={this.menuClick}
                    ></i>
                </div>
            )
            // jsx.pop();
            return parentJsx;
        }

        let getQueyKeys = () => {

            let refHtml = []
            for (let i = 0; i < conditions.length; i++) {
                let className = "key-one-row";
                let moreViewId = (conditions[i].attrcode === 'pk_tradetype' || conditions[i].attrcode === 'transtypecode') ? 'more-view-btn' : ''
                if (i >= twoColNums) className = "key-two-row";
                if (
                    conditions[i].attrcode === 'pk_tradetype'
                    ||
                    conditions[i].attrcode === 'transtypecode'
                ) className = "key-two-row tradetype-wrap"
                refHtml.push(
                    <NCDiv fieldid={conditions[i].attrcode} areaCode={NCDiv.config.Group}>
                        <div className={className}>
                            <table>
                                <tbody>
                                    <tr>
                                        <td className='td-label'>
                                            {conditions[i].label}：
                                    </td>
                                        <td colSpan="2" className='td-con'>
                                            {getCondition(conditions[i])}
                                            <span
                                                onClick={() => { this.setState({ showMore: true }, () => { this.updateTradetypeOptions() }) }}
                                                className='arrow-down'
                                                id={moreViewId}
                                                style={{
                                                    display: (conditions[i].attrcode === 'pk_tradetype' || conditions[i].attrcode === 'transtypecode') && !showMore ? 'block' : 'none'
                                                }}
                                            >
                                                {this.state.multiLang['1056common-0010']/*展开*/}
                                            </span>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </NCDiv>
                )
            }
            return refHtml;;
        }

        let getCusQueryKey = () => {
            if (cusType == "rp") {
                return ([
                    <td className='td-label' style={{ top: '-2px', verticalAlign: 'middle' }}>
                        <span className='more-condition'>{this.state.multiLang['1056common-0011']/*模糊搜索：*/}：</span>
                    </td>,
                    <td>
                        <div>
                            <NCSelect
                                fieldid="fuzzy-query"
                                className="fuzzyquery"
                                height="24px"
                                tags
                                supportSearch={true}
                                searchPlaceholder={this.state.multiLang['1056common-0012']/*标签模式*/}
                                placeholder={this.state.multiLang['1056common-0013']/*模糊查询*/}
                                value={this.state.fuzzyQueryValue}
                                data={fuzzyquerychild}
                                onSearch={onFuzzyChange.bind(this)}
                                onChange={(data) => {
                                    this.setState({
                                        fuzzyQueryValue: data
                                    });
                                    onFuzzySelected.call(this, data)
                                }}
                            >
                            </NCSelect>
                        </div>
                    </td>
                ]
                )
            } else if (cusType.indexOf("tp") > -1) {
                return ([
                    <td className='td-label' style={{ top: '-2px', verticalAlign: 'middle', display: hideBarCode ? 'none' : '' }}>
                        <span className='more-condition'>{this.state.multiLang['1056common-0014']/*更多条件：*/}：</span>
                    </td>,
                    <td>
                        <div className={this.state.barcodeVal && this.state.barcodeVal.length > 0 ? "barcode barcode-focus" : "barcode"} style={{ display: hideBarCode ? 'none' : '' }}>
                            <NCFormControl
                                fieldid="barcode-query"
                                value={this.state.barcodeVal}
                                onChange={(val) => {
                                    if (val) {
                                        this.setState({ barcodeVal: val, hasBarCode: true })
                                    } else {
                                        this.setState({ barcodeVal: val, hasBarCode: false }, () => {
                                            this.barcodeQuery()
                                        })
                                    }
                                }}
                                type='search'
                                onSearch={this.barcodeQuery}
                                placehoder={this.state.multiLang['1056common-0051']/*条码扫描*/}
                            />
                            <i className='iconfont icon-saoyisao nc-theme-common-font-c'></i>
                        </div>
                        <div style={{ marginLeft: hideBarCode ? '18px' : '' }}>
                            <NCSelect
                                fieldid="fuzzy-query"
                                className="fuzzyquery"
                                height="24px"
                                tags
                                supportSearch={true}
                                searchPlaceholder={this.state.multiLang['1056common-0012']/*标签模式*/}
                                placeholder={this.state.multiLang['1056common-0013']/*模糊查询*/}
                                data={fuzzyquerychild}
                                onSearch={onFuzzyChange.bind(this)}
                                value={this.state.fuzzyQueryValue}
                                onChange={(data) => {
                                    this.setState({
                                        fuzzyQueryValue: data
                                    });
                                    onFuzzySelected.call(this, data)
                                }}
                            >
                            </NCSelect>
                        </div>
                        <div className="auto-open" style={{ display: hideBarCode ? 'none' : '' }}>
                            <NCCheckbox
                                onChange={() => {
                                    this.setState({ autoOpenChecked: !this.state.autoOpenChecked })
                                }}
                                checked={this.state.autoOpenChecked}
                            >{this.state.multiLang['1056common-0015']/*自动打开：*/}</NCCheckbox>
                        </div>
                        <div className='cashier-reject'
                            style={{ display: this.props.showCashierReject ? 'block' : 'none' }}
                        >
                            <NCCheckbox
                                checked={this.props.queryKey.iscmpreject == 'Y' ? true : false}
                                onChange={(val) => {
                                    this.setState({
                                        showCahierReject: val
                                    })
                                    this.props.handleConditionChange('iscmpreject', val ? 'Y' : 'N');
                                }}
                            >{this.state.multiLang['1056common-0050'] || '出纳驳回'/* 出纳驳回 */}</NCCheckbox>
                        </div>
                    </td>
                ]
                )
            }
        }

        return (
            <NCDiv areaCode={NCDiv.config.SEARCH}>
                <div id="SysComponentsWorkbenchSearcharea" class="nc-theme-gray-area-bgc nc-theme-area-split-bc">
                    <div>
                        <div>
                            {this.state.hideFat ?
                                (<div className={'thin-filter-wrap'}>
                                    {getQueyKeyWithThinStyle()}

                                </div>)
                                :
                                (<div className={'fat-filter-wrap'}>
                                    {getQueyKeys()}
                                    <div className="key-two-row">
                                        <table>
                                            <tbody>
                                                <tr>
                                                    {getCusQueryKey()}
                                                    <td className="menu-icon-td" style={{
                                                        display: this.props.disabledTypeChange ? 'none' : 'block'
                                                    }}>
                                                        <i className='menu-type-icon iconfont icon-xiangshang1 nc-theme-btn-secondary' onClick={
                                                            () => {
                                                                this.changeHideFat(true);
                                                            }
                                                        }></i>
                                                        <i
                                                            className={`menu-type-icon iconfont ${this.state.menuShowType.type} nc-theme-btn-secondary`}
                                                            title={this.state.menuShowType.title}
                                                            onClick={this.menuClick}
                                                        ></i>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>)
                            }
                        </div>
                    </div>
                </div>
            </NCDiv>
        )
    }
}

export default WorkbenchSearcharea;